package com.zq.sysuser.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.zq.common.logs.AsyncLogService;
import com.zq.common.logs.SysOperLog;
import com.zq.sysuser.dao.entity.User;
import com.zq.sysuser.mapper.SysOperLogMapper;
import com.zq.sysuser.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service
public class AsyncOperLogServiceImpl implements AsyncLogService {

    @Resource
    private SysOperLogMapper sysOperLogMapper;

    @Resource
    private IUserService userService;


    @Async      // 异步执行保存日志操作
    @Override
    public void saveSysOperLog(SysOperLog sysOperLog) {
        // 保存日志
        com.zq.sysuser.dao.entity.SysOperLog sysOperLog2 = new com.zq.sysuser.dao.entity.SysOperLog();
 BeanUtils.copyProperties(sysOperLog, sysOperLog2);
        // 获取当前账号 id 的 Account-Session (必须是登录后才能调用)
//        SaSession session = StpUtil.getSession();
//        session.get("id");
        Object loginId = StpUtil.getSession().getLoginId();
        User byId = userService.getById((Serializable) loginId);
        if (byId == null) {
         throw new RuntimeException("用户不存在");
        }
        sysOperLog2.setOperName(byId.getUsername());
        sysOperLogMapper.insert(sysOperLog2);
    }

}